package com.intelligentpension.kotlinbluetooth.ble

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.material.textfield.TextInputLayout
import com.hjq.toast.ToastUtils
import com.intelligentpension.kotlinbluetooth.R
import com.intelligentpension.kotlinbluetooth.bt.BtBase
import com.intelligentpension.kotlinbluetooth.bt.BtServer
import com.orhanobut.logger.Logger

class BleServerActivity : AppCompatActivity(), View.OnClickListener, BtBase.Listener {

    private val startActivityFor =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            //此处是跳转的result回调方法
            if (it.data != null && it.resultCode == Activity.RESULT_OK) {
                var uri: Uri = it.data!!.data as Uri
                val path = uri.path
                ToastUtils.show("文件的路径是$path")
//                it.data?.getStringExtra(NewWordActivity.EXTRA_REPLY)?.let { reply ->
//                    val word = Word(reply)
//                    wordViewModel.insert(word)
//                }
                if (path != null) {
                    mServer.sendFile(path)
                }else{
                    ToastUtils.show("找不到文件路径")
                }
            } else {
            }
        }

    private lateinit var mTv: TextView
    private lateinit var mTextSend: TextInputLayout
    private lateinit var mSendButton: Button
    private lateinit var mSendFile: Button
    private lateinit var mTvLog: TextView
    private lateinit var mServer: BtServer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ble_server)
        mTv = findViewById<TextView>(R.id.tv_tip)
        mTextSend = findViewById<TextInputLayout>(R.id.text_send)

        mSendButton = findViewById<Button>(R.id.send_button)
        mSendButton.setOnClickListener(this@BleServerActivity)
        mSendFile = findViewById<Button>(R.id.send_file)
        mSendFile.setOnClickListener(this@BleServerActivity)
        mTvLog = findViewById<TextView>(R.id.tv_log)

        mServer = BtServer(this@BleServerActivity, this@BleServerActivity)
    }

    override fun onDestroy() {
        super.onDestroy()
        mServer.unListener()
        mServer.closeSocket()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.send_button -> {
                if (mServer.isConnected(null)) {
                    var msg = mTextSend.editText!!.text.toString()
                    if (msg.isEmpty()) {
                        ToastUtils.show("消息不能为空")
                    } else {
                        mServer.sendMsg(msg)
                    }
                }
            }
            R.id.send_file -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                intent.type = "*/*"
                startActivityFor.launch(intent)
            }
        }
    }

    //这是接收到的信息
    @SuppressLint("MissingPermission")
    override fun socketNotify(state: Int, obj: Any?) {
        if (isDestroyed) return
        var msg: String = ""
        when (state) {
            BtBase.Listener.CONNECTED -> {
                var dev = obj as BluetoothDevice
                var msg = String.format("与%s(%s)连接成功", dev.name, dev.address)
                mTv.text = msg
                Logger.e("连接的眼啦名字文字渲染不上去")
            }
            BtBase.Listener.DISCONNECTED -> {
                mServer.listen()
                msg = "连接断开,正在重新监听......"
                mTv.text = msg
            }
            BtBase.Listener.MSG -> {
                msg = String.format("\n%s", obj)
                mTvLog.append(msg)
                Logger.e("msg")
            }
        }
        ToastUtils.show("当前状态=="+state+"信息"+msg)
    }
}